<template>
	<view class="base-cloud" :style="{width:'95vw', height : '340rpx',margin:'0 auto'}">
		<!-- <image :src="canvasBg" class="canvas_bg"></image> -->
		<view class="canvas_bg1" :style="'background-image: url(' + gginner_bg+ ')'">

		</view>
		<view class="father" id="canvas">
			<view :class="{op0 : !ready }">
				<slot></slot>
			</view>

		</view>

		<canvas :style="{width:'95vw', height : '340rpx'}" class="abs" :disable-scroll="true" @touchstart="touchstart"
			@touchend="touchend" @touchmove="touchmove" canvas-id="scratch-card"></canvas>
	</view>
	</view>
</template>

<script>
	let ctx = null;
	export default {
		name: "scratch-card",
		props: {
			ismove: {
				type: Boolean,
				default: false
			},
			percentage: { //刮开百分之多少的时候开奖
				type: Number,
				default: 35
			},
			touchSize: { //触摸画笔大小
				type: Number,
				default: 20
			},
			fillColor: { //未刮开图层时的填充色
				type: String,
				default: '#ddd'
			},
			watermark: { //水印文字
				type: String,
				default: '刮一刮'
			},
			watermarkColor: { //水印文字颜色
				type: String,
				default: '#c5c5c5'
			},
			watermarkSize: { //水印文字大小
				type: Number,
				default: 14
			},
			title: { //提示文字
				type: String,
				default: ''
			},
			titleColor: { //提示文字颜色
				type: String,
				default: '#888'
			},
			titleSize: { //提示文字大小
				type: Number,
				default: 24
			},
			disabled: { //是否禁止刮卡
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				gginner_bg: "",
				canvasBg: "",
				myresultImg: "",
				firstTouch: true,
				width: 0,
				height: 0,
				startX: null,
				startY: null,
				computing: false,
				complete: false,
				reset: false,
				ready: false,
				storePoints: []
			};
		},
		watch: {
			ismove(val) {
				this.canMove = val
			},
		},
		mounted() {
			this.myresultImg = `${uni.$http.baseUrl}/upload/we/scratchcard/scale1.png`;
			this.canvasBg = `${uni.$http.baseUrl}/upload/we/scratchcard/scale2.png`;

			this.gginner_bg = this.canvasBg
			this.canMove = this.ismove
			ctx = uni.createCanvasContext("scratch-card", this);
			this.getRect();


		},
		methods: {

			getRect: function(e) {
				const query = uni.createSelectorQuery().in(this);
				query.select('#canvas').boundingClientRect(data => {
					this.width = data.width;
					this.height = data.height;
					setTimeout(e => {
						this.init();
					}, 20);
				}).exec();
			},

			init: function(e) {
				console.log("initinit")
				var _this = this;
				this.computing = false;
				this.complete = false;
				this.reset = false;
				this.ready = false;
				ctx.clearRect(0, 0, this.width, this.height);
				//绘制画布
				// ctx.setFillStyle(this.fillColor);
				// ctx.fillRect(0, 0, this.width, this.height);



				this.ready = true;
				//绘制文字水印
				var src = `${uni.$http.baseUrl}/upload/we/scratchcard/scale1.png`
				uni.getImageInfo({
					src: src,
					success: (res) => {
						// const aspectRatio = res.width / res.height;
						// const canvasWidth = _this.width; // 假设屏幕宽度为750px
						// const canvasHeight = canvasWidth / aspectRatio;
						// ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight);
						// ctx.draw();
						const imgWidth = res.width;
						const imgHeight = res.height;

						// 获取canvas容器的宽高
						const canvasWidth = uni.upx2px(720); // 将uniapp的upx单位转换为px
						const canvasHeight = uni.upx2px(400);

						// 计算图片的宽高比和canvas容器的宽高比
						const imgRatio = imgWidth / imgHeight;
						const canvasRatio = canvasWidth / canvasHeight;

						// 根据比例调整图片的显示大小
						let imgDisplayWidth, imgDisplayHeight;
						if (imgRatio > canvasRatio) {
							imgDisplayWidth = canvasWidth;
							imgDisplayHeight = canvasWidth / imgRatio;
						} else {
							imgDisplayWidth = canvasHeight * imgRatio;
							imgDisplayHeight = canvasHeight;
						}

						// 在canvas上绘制图片 top  (canvasHeight -imgDisplayHeight) / 2
						ctx.drawImage(res.path, (canvasWidth - imgDisplayWidth) / 2, 0, imgDisplayWidth,
							imgDisplayHeight);
						ctx.draw();
					}
				});


				// const image = uni.createImage();
				// image.src = src;
				// image.onload = () => {
				// 	ctx.drawImage(src, 0, 0, _this.width, _this.height);
				// };


				// this.fillWatermark();
				// //绘制标题
				// this.fillTitle();
				// ctx.draw();
			},

			/**
			 * 绘制文字水印
			 */
			fillWatermark: function(e) {
				if (!this.watermark) {
					return;
				}
				var width = this.watermark.length * this.watermarkSize;
				ctx.save();
				ctx.rotate(-10 * Math.PI / 180);
				let x = 0;
				let y = 0;
				let i = 0;
				while ((x <= this.width * 5 || y <= this.height * 5) && i < 300) {
					ctx.setFillStyle(this.watermarkColor);
					ctx.setFontSize(this.watermarkSize);
					ctx.fillText(this.watermark, x, y);
					x += width + width * 1.6;
					if (x > this.width && y <= this.height) {
						x = -Math.random() * 100;
						y += this.watermarkSize * 3;
					}
					i++;
				}
				ctx.restore();
			},

			/**
			 * 绘制标题
			 */
			fillTitle: function(e) {
				if (!this.title) {
					return;
				}
				var width = this.width / 2 - 40
				ctx.setTextAlign("center");
				ctx.setTextBaseline("middle");
				ctx.setFillStyle(this.titleColor);
				ctx.setFontSize(this.titleSize);
				ctx.fillText(this.title, width, this.height / 2);
			},

			touchstart: function(e) {


				this.startX = e.touches[0].x;
				this.startY = e.touches[0].y;
			},

			touchend: function(e) {
				this.getFilledPercentage();
			},

			touchmove: function(e) { //this.complete &

				if (this.disabled) {
					console.log("touchmove")
					return;
				}
				if (this.firstTouch) {
					this.$emit("startCallback", {});
					console.log("startCallback")
					this.firstTouch = false;
				}

				// ctx.globalCompositeOperation = 'destination-out'; 
				ctx.moveTo(this.startX, this.startY);
				// ctx.beginPath();
				// ctx.arc(this.startX, this.startY, 20, 0, Math.PI * 20);
				// ctx.fill();
				ctx.clearRect(this.startX, this.startY, this.touchSize, this.touchSize);
				ctx.draw(true);
				//记录移动点位
				this.startX = e.touches[0].x;
				this.startY = e.touches[0].y;
			},

			getFilledPercentage: function(e) {
				console.log(this.computing)
				if (this.computing) {
					return;
				}
				if (this.disabled) {
					uni.showToast({
						title: this.title,
						icon: "error"
					})
					return
				}
				this.computing = true;
				uni.canvasGetImageData({
					canvasId: 'scratch-card',
					x: 0,
					y: 0,
					width: this.width,
					height: this.height,
					success: (res) => {
						let pixels = res.data;
						let transPixels = [];
						for (let i = 0; i < pixels.length; i += 4) {
							if (pixels[i + 3] < 128) {
								transPixels.push(pixels[i + 3]);
							}
						}
						var percent = (transPixels.length / (pixels.length / 4) * 100).toFixed(2);
						console.log("percent", percent)
						console.log("this.percentage", this.percentage)
						if (percent >= this.percentage & !this.firstTouch) {
							this.success();
						}
						this.computing = false;

						console.log(percent)
					},
					fail: function(e) {
						console.log(e);
					},
				}, this);
			},

			success: function(e) {

				this.complete = true;
				// if (this.reset) {
				// 	return;
				// }
				this.reset = true;
				ctx.moveTo(0, 0);
				ctx.clearRect(0, 0, 1000, 600);
				ctx.stroke();
				ctx.draw(true);
				console.log("complete")
				this.$emit("complete", {});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.base-cloud {
		position: relative;
		overflow: hidden;
		z-index: 0;

		.abs {
			position: absolute;
			width: 95vw;

			height: 340rpx;
			z-index: 2;

		}

		.father {
			position: absolute;
			left: 0;
			right: 0;
			z-index: 1;
		}

		.canvas_bg {
			position: absolute;
			width: 95vw;
			z-index: 2;
			height: 340rpx;

		}

		.canvas_bg1 {
			position: absolute;
			background-size: contain;
			width: 95vw;
			z-index: 0;
			height: 340rpx;

		}
	}
</style>